<template>
  <view class="commemorative-container">
    <!-- 操作栏 -->
    <view class="operation-bar">
      <view class="action-buttons">
        <button class="btn primary" @tap="showEditForm(null)" v-if="isAdmin">
          <uni-icons type="plus" size="16"></uni-icons>
          新建卡片
        </button>
      </view>
    </view>

    <!-- 统计面板 -->
    <view class="stats-panel">
      <view class="stat-item">
        <text class="value">{{ total }}</text>
        <text class="label">总卡片数</text>
      </view>
    </view>

    <!-- 卡片列表 -->
    <scroll-view class="card-list" scroll-y>
      <view 
        v-for="card in cardList"
        :key="card._id"
        class="card-item"
      >
        <image 
          class="card-image"
          :src="card.image || '/static/default-card.png'"
          mode="aspectFill"
          @tap="previewImage(card.image)"
        />
        <view class="card-content">
          <view class="card-header">
            <text class="title">{{ card.name }}</text>
          </view>
          
          <view class="card-meta">
            <view class="meta-item">
              <uni-icons type="star" size="14" color="#f1c40f"></uni-icons>
              <text class="points">{{ card.requiredPoints }} 积分</text>
            </view>
            <text class="create-time">
              {{ card.createTime | formatDate('YYYY-MM-DD') }}
            </text>
          </view>

          <view class="card-desc" v-if="card.desc">
            {{ card.desc || '暂无描述' }}
          </view>

          <view class="card-actions" v-if="isAdmin">
            <button class="btn icon-btn" @tap="showEditForm(card)">
              <uni-icons type="compose" size="18"></uni-icons>
            </button>
           <!-- <button class="btn icon-btn danger" @tap="handleDelete(card._id)">
              <uni-icons type="trash" size="18"></uni-icons>
            </button> -->
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog" :mask-click="false">
      <uni-popup-dialog 
        mode="form" 
        :title="editForm._id ? '编辑纪念卡' : '新建纪念卡'"
        @confirm="submitForm"
      >
        <uni-forms :model="editForm" :rules="formRules">
          <uni-forms-item label="卡片名称" name="name">
            <uni-easyinput 
              v-model="editForm.name" 
              placeholder="请输入卡片名称"
              trim="both"
            />
          </uni-forms-item>

          <uni-forms-item label="所需积分" name="requiredPoints">
            <uni-number-box 
              v-model="editForm.requiredPoints"
              :min="100"
              :max="99999"
              :step="100"
            />
          </uni-forms-item>

          <uni-forms-item label="封面图片" name="image">
            <uni-file-picker 
              v-model="editForm.image"
              file-mediatype="image"
              limit="1"
              :image-styles="imageStyle"
            />
          </uni-forms-item>

          <uni-forms-item label="卡片描述">
            <uni-easyinput
              type="textarea"
              v-model="editForm.desc"
              placeholder="请输入卡片描述（可选）"
              :maxlength="200"
              show-count
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cardList: [],
      total: 0,
      isAdmin: true,
      
      editForm: {
        name: '',
        requiredPoints: 100,
        image: '',
        desc: ''
      },
      
      formRules: {
        name: {
          rules: [{ required: true, errorMessage: '请输入卡片名称' }]
        },
        requiredPoints: {
          rules: [
            { required: true, errorMessage: '请输入所需积分' },
            { minimum: 100, errorMessage: '积分需≥100' }
          ]
        },
        image: {
          rules: [{ required: true, errorMessage: '请上传封面图片' }]
        }
      },
      
      imageStyle: {
        width: '200rpx',
        height: '200rpx'
      }
    }
  },

  filters: {
    formatDate(timestamp) {
      if (!timestamp) return '未知日期'
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`
    }
  },

  methods: {
    formatDate(timestamp) {
      if (!timestamp) return '未知日期'
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`
    },
    async loadData() {
      try {
        const { result } = await uniCloud.callFunction({
          name: 'getCommemorativeCards',
          data: { action: 'list' }
        })

        if (result?.code === 200) {
          this.cardList = result.data.list.map(item => ({
            _id: item._id,
            name: item.name,
            image: item.image,
            requiredPoints: item.requiredPoints,
            createTime: item.createTime || Date.now(),
            desc: item.desc || '暂无描述'
          }))
          this.total = result.data.total
        }
      } catch (error) {
        uni.showToast({ title: '数据加载失败', icon: 'none' })
      }
    },

    showEditForm(card) {
      this.editForm = card ? { 
        ...card,
        image: { tempFilePaths: [card.image] }
      } : {
        name: '',
        requiredPoints: 100,
        image: null,
        desc: ''
      }
      this.$refs.editPopup.open()
    },

    async submitForm() {
      try {
        const formData = { ...this.editForm }
        formData.image=formData.image[0].fileID
        if (formData.image?.tempFiles?.[0]) {
          const uploadRes = await uniCloud.uploadFile({
            filePath: formData.image.tempFiles[0].path,
            cloudPath: `cards/${Date.now()}`
          })
        }

        const action = formData._id ? 'update' : 'create'
        await uniCloud.callFunction({
          name: 'getCommemorativeCards',
          data: { action, data: formData }
        })

        uni.showToast({ title: '操作成功' })
        this.loadData()
        this.$refs.editPopup.close()
      } catch (error) {
        uni.showToast({ title: '操作失败', icon: 'none' })
      }
    },

    async handleDelete(cardId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要永久删除该纪念卡吗？',
        success: async (res) => {
          if (res.confirm) {
            await uniCloud.callFunction({
              name: 'getCommemorativeCards',
              data: { action: 'delete', id: cardId }
            })
            this.loadData()
          }
        }
      })
    },

    previewImage(url) {
      if (url) uni.previewImage({ urls: [url] })
    }
  },

  mounted() {
    this.loadData()
  }
}
</script>

<style lang="scss" scoped>
/* 保持原有样式，移除.status-tags相关样式 */
.commemorative-container {
  padding: 20rpx;
  background: #f5f7fa;
  min-height: 100vh;
}

.operation-bar {
  margin-bottom: 30rpx;
  padding: 0 20rpx;
  
  .btn.primary {
    background: #3498db;
    color: white;
    padding: 12rpx 24rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
  }
}

.stats-panel {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
  padding: 0 20rpx;
  
  .stat-item {
    flex: 1;
    background: white;
    padding: 24rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
    
    .value {
      display: block;
      font-size: 36rpx;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 8rpx;
    }
    
    .label {
      font-size: 24rpx;
      color: #7f8c8d;
    }
  }
}

.card-list {
  padding: 0 20rpx;
}

.card-item {
  background: white;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.08);
  
  .card-image {
    width: 100%;
    height: 320rpx;
    border-radius: 16rpx 16rpx 0 0;
  }

  .card-content {
    padding: 24rpx;
    
    .card-header {
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: 500;
        color: #2c3e50;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .card-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .points {
        color: #e67e22;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        gap: 8rpx;
      }
      
      .create-time {
        color: #95a5a6;
        font-size: 24rpx;
      }
    }
    
    .card-desc {
      color: #666;
      font-size: 26rpx;
      line-height: 1.6;
      margin-bottom: 24rpx;
    }

    .card-actions {
      display: flex;
      justify-content: flex-end;
      gap: 20rpx;
      
      .icon-btn {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f8f9fa;
        
        &.danger {
          color: #e74c3c;
        }
      }
    }
  }
}
</style>